package com.example.dsplatform.Controller;

import cn.hutool.core.io.FileUtil;
import com.example.dsplatform.pojo.Entity.ResponseResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.Servlet;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/file")
public class FileController {

    public static final String Root_Path = System.getProperty("user.dir")+File.separator+"files";
    @Value("${ip:localhost}")
    String ip;
    @Value("${server.port}")
    String port;
    @PutMapping("/upload")
    public ResponseResult uploadFile (MultipartFile file) throws IOException {
        String oraginalFilename = file.getOriginalFilename();
        String mainName = FileUtil.mainName(oraginalFilename);
        String extName = FileUtil.extName("文件的后缀");
        String projectPath = System.getProperty("user.dir");
        File parentFile = new File(Root_Path);
        String filePath= projectPath+"\\file";
        String fileRealPath = filePath+"\\"+oraginalFilename;
        if(!parentFile.exists()){
            parentFile.mkdirs();
        }
       /* if(!saveFile.getParentFile().exists()){
            saveFile.getParentFile().mkdir();
        }*/
        File saveFile = new File(Root_Path+File.separator+oraginalFilename);
        if (saveFile.exists()) {
            oraginalFilename = System.currentTimeMillis()+"_"+mainName+"."+extName;
            saveFile = new File(Root_Path+File.separator+oraginalFilename);
        }
        file.transferTo(saveFile);
        String url = "http://"+ ip +":"+ port+"/file/download/"+oraginalFilename;
        return new ResponseResult(200,"上传成功",url);
    }



    @GetMapping("/download/{filename}")
    public ResponseResult download(@PathVariable String filename, HttpServletResponse response) throws IOException {
        String filePath = Root_Path + File.separator + filename;
        if (!FileUtil.exist(filePath)) {
            return new ResponseResult<>(204, "下载失败");

        }
        byte[] bytes = FileUtil.readBytes(filePath);
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();

        return new ResponseResult<>(200, "下载完成");
    }

}
